package com.myproject.controller;

import com.myproject.dto.CaptchaDTO;
import com.myproject.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 验证码控制器
 */
@RestController
@RequestMapping("/api/captcha")
public class CaptchaController {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String CAPTCHA_PREFIX = "captcha:";
    private static final long CAPTCHA_EXPIRE = 5; // 5分钟

    /**
     * 获取验证码
     */
    @GetMapping
    public CaptchaDTO getCaptcha() {
        // 生成验证码
        String[] captcha = CaptchaUtil.generateCaptcha();
        String captchaKey = UUID.randomUUID().toString();
        
        // 存储到Redis
        redisTemplate.opsForValue().set(
            CAPTCHA_PREFIX + captchaKey, 
            captcha[1], 
            CAPTCHA_EXPIRE, 
            TimeUnit.MINUTES
        );
        
        // 返回结果
        CaptchaDTO dto = new CaptchaDTO();
        dto.setCaptchaKey(captchaKey);
        dto.setCaptchaImage(captcha[0]);
        return dto;
    }
}